package com.tjcd.project.library_base.base.bean;

import com.blankj.utilcode.util.LogUtils;
import com.tjcd.project.library_base.base.rsaUtils.RSAUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.PublicKey;
import java.util.Iterator;

import okhttp3.RequestBody;

/**
 * @Author jiangKunKun
 * @CreateDate 2021/7/6
 * @Description RequestBody封装
 * @SpittingGrooves
 */
public class RequestBean extends BaseJsonRequestBean {

    /**
     * 构造方法 公参可以在此方法中进行添加
     */
    public RequestBean() {
    }

    /**
     * RequetBody NoEncrypt
     * @return
     */
    public RequestBody getFinalRequetBodyNoEncrypt() {
        LogUtils.e("连接原始参数:" + this.toString());
        return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), this.toString());
    }

    /**
     * FormBody NoEncrypt
     * @return
     */
    public RequestBody getFinalFormBodyNoEncrypt() {
        LogUtils.e("连接原始参数:" + this.toString());
        StringBuffer data = new StringBuffer();
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(this.toString());
            Iterator it = jsonObject.keys();
            while(it.hasNext()){
                // 获得key
                String key = (String) it.next();
                // 获得value
                String value = jsonObject.getString(key);
                data.append(key).append("=").append(value).append("&");
            }
            String jso = data.substring(0, data.length() - 1);
            return RequestBody.create(okhttp3.MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"), jso);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取json格式的RequestBody参数封装
     *
     * @return
     */
    public RequestBody getFinalRequestBody() {
        LogUtils.e("连接原始参数:" + this.toString());
        // 参数加密操作
        PublicKey publicKey = null;
        String encrypt = "";
        try {
            publicKey = RSAUtil.getPublicKey(RSAUtil.PUBLIC_KEY);
            encrypt = "{\"rsa\":\"" + RSAUtil.encrypt(this.toString(), publicKey) + "\"}";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), encrypt);
    }
}
